package com.hangwei.paperless;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hangwei.paperless.model.bean.CardToSeal;
import com.hangwei.paperless.model.bean.PicResult;
import com.hangwei.paperless.model.entity.CameraEvent;
import com.hangwei.paperless.net.NetManager;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.Density;
import com.hangwei.paperless.utils.NFCCallBack;
import com.hangwei.paperless.view.BaseView;
import com.hangwei.paperless.view.MainProgressTitle;
import com.hangwei.paperless.view.repair.AcceptCheck;
import com.hangwei.paperless.view.repair.AssemblyRecord;
import com.hangwei.paperless.view.repair.BasicInfo;
import com.hangwei.paperless.view.repair.BreakDownRecord;
import com.hangwei.paperless.view.repair.CheckRecord;
import com.hangwei.paperless.view.repair.CleanRecord;
import com.hangwei.paperless.view.repair.FinalCheck;
import com.hangwei.paperless.view.repair.SubProcess;
import com.hangwei.paperless.view.repair.TestRecord;
import com.hangwei.paperless.widget.CardSealPop;
import com.hangwei.paperless.widget.MainBottomPopupWindow;
import com.hangwei.paperless.widget.MainListPopupWindow;
import com.hangwei.paperless.widget.PicDialog;
import com.twelve.all.base.CameraActivity;
import com.twelve.all.base.NFCApp;
import com.twelve.all.net.CallBack;
import com.twelve.all.net.ResponseInfo;
import com.twelve.all.nfc.Constants;
import com.twelve.all.nfc.MCReader;
import com.twelve.all.nfc.PreferencesUtil;
import com.twelve.all.nfc.Utils;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;

import rx.Observable;

public class MainRepairActivity extends CameraActivity implements View.OnClickListener, MainProgressTitle.OnProgressItemClickListener {

    public static String pwoNo;
    public String objectId;//上传绑定对象id
    private ImageView mIvList;
    private MainListPopupWindow mPopupWindow;
    private MainProgressTitle mMainProgressTitle;
    private FrameLayout mMainContent;

    private MainBottomPopupWindow mMainBottomPopupWindow;
    private BaseView mBaseView;
    private String mUserId;
    private LoadingDialog mDialog;
    private PicDialog mPicDialog;

    public void setStep(String step) {
        mStep = step;
    }

    private String mStep;
    private boolean mCanCard;
    private CardSealPop mCardSealPop;
    private String stepId;
    private NFCCallBack mNFCCallBack;
    private String mWoNo;
    private String mPn;
    private String mSn;
    private String mDescription;

    public String getBillId() {
        return mBillId;
    }

    private String mBillId;

    public static String mStepId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mIvList = (ImageView) findViewById(R.id.ivList);
        TextView tvBaseWorkCard = (TextView) findViewById(R.id.tvBaseWorkCard);
        TextView tvPN = (TextView) findViewById(R.id.tvPN);
        TextView tvSN = (TextView) findViewById(R.id.tvSN);
        TextView tvDes = (TextView) findViewById(R.id.tvDes);
        LinearLayout back = (LinearLayout) findViewById(R.id.back);
        FrameLayout progressContent = findViewById(R.id.progressContent);
        mUpLoadNow = false;
        back.setOnClickListener(this);
        mIvList.setOnClickListener(this);

        mMainProgressTitle = new MainProgressTitle(this);
        mMainProgressTitle.setOnProgressItemClickListener(this);
        progressContent.addView(mMainProgressTitle.getProgressView());

        mMainContent = findViewById(R.id.mainContent);

        mUserId = SPUtil.getString(SPKey.Account.USER_ID);
        mDialog = new LoadingDialog(this);

        Intent intent = getIntent();
        mBillId = intent.getStringExtra("id");
        mStep = intent.getStringExtra("step");
        mWoNo = intent.getStringExtra("woNo");
        mPn = intent.getStringExtra("pn");
        mSn = intent.getStringExtra("sn");
        mDescription = intent.getStringExtra("description");
        tvBaseWorkCard.setText(mWoNo);
        tvPN.setText(mPn);
        tvSN.setText(mSn);
        tvDes.setText(mDescription);
        mMainProgressTitle.refreshViewByStep(mStep);
        fixedAndLoad(mStep);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CAMERA_IMAGE || requestCode == RESULT_LOAD_IMAGE)
            if (urls.size() != 0) {
                LoadingDialog dialog = new LoadingDialog(MainRepairActivity.this, "图片处理中");
                dialog.show();
                String userId = SPUtil.getString(SPKey.Account.USER_ID);
                new Model<ResponseInfo<PicResult>>() {
                    @Override
                    protected void onCompressFinished() {
                        dialog.setMsg("正在上传");
                    }

                    @Override
                    protected void onCompleted() {
                        dialog.dismiss();
                        ToastUtil.showCenterToast("上传成功");
                        urls.clear();
                        EventBus.getDefault().post(new CameraEvent());
                    }

                    @Override
                    protected void onError(Throwable e) {
                        urls.clear();//上传失败也要清除保存的图片本地路径，避免与下次选择的图片混在一起
                    }

                    @Override
                    protected void onNext(ResponseInfo<ResponseInfo<PicResult>> responseInfoResponseInfo) {

                    }

                    @Override
                    protected Observable<ResponseInfo<ResponseInfo<PicResult>>> getObservable(String url, String base64) {
                        return NetManager.getResponseInfoAPI().uploadFile(userId,pwoNo , objectId, url, base64);
                    }
                }.upLoadAllCompressedImg();
            }
    }

    @Override
    protected void upLoadCompressedImg(File file, String base64, String picturePath) {

    }

    @Override
    protected void showCompressedPic(Bitmap bitmap, String picturePath) {
//        EventBus.getDefault().post(new CameraEvent(bitmap, picturePath));
    }

    public void fixedAndLoad(String step) {
        if (TextUtils.isEmpty(step)) {
            ToastUtil.showCenterToast("步骤加载错误");
        } else {
            String[] split = step.split("-");
            try {
                int mainStep = Integer.parseInt(split[0]);
                int subStep = 0;
//                try {
//                    if (mainStep != 0) {
////                        subStep = Integer.parseInt(split[1]);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    loadView(mainStep, subStep);
//                }
                if (mainStep > 9)
                    throw new IllegalAccessException("mainStep = " + mainStep + "-------步骤错误");
                loadView(mainStep, subStep);
                mMainProgressTitle.refreshViewByStep(step);
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showCenterToast("步骤解析错误");
                finish();
            }
        }
    }

    private void loadView(int mainStep, int subStep) {
        switch (mainStep) {
            case 0:
                mBaseView = new BasicInfo(this);
                break;
            case 1:
                mBaseView = new AcceptCheck(this);
                break;
            case 2:
                mBaseView = new BreakDownRecord(this);
                break;
            case 3:
                mBaseView = new CleanRecord(this);
                break;
            case 4:
                mBaseView = new CheckRecord(this);
                break;
            case 5:
                mBaseView = new SubProcess(this);
                break;
            case 6:
                mBaseView = new AssemblyRecord(this);
                break;
            case 7:
                mBaseView = new TestRecord(this);
                break;
            case 8:
                mBaseView = new FinalCheck(this);
                break;
        }
        mBaseView.setSubStep(subStep);
        mMainContent.removeAllViews();
        mMainContent.addView(mBaseView.getItemView());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ivList:
                if (mPopupWindow == null)
                    mPopupWindow = new MainListPopupWindow(this, false) {
                        @Override
                        public void showEPA() {
                            Intent intent = new Intent(MainRepairActivity.this, EngTreatmentEditActivity.class);
                            intent.putExtra("billId", mBillId);
                            intent.putExtra("stepId", mStepId);
                            intent.putExtra("woNo", mWoNo);
                            intent.putExtra("pn", mPn);
                            intent.putExtra("sn", mSn);
                            intent.putExtra("description", mDescription);
                            startActivity(intent);
                            mPopupWindow.dismiss();
                        }

                        @Override
                        public void showApply() {
//                            showBottomPopupWindow(BottomPopType.NA);
//                            mPopupWindow.dismiss();
                        }
                    };
                mPopupWindow.showAsDropDown(mIvList, Density.dip2px(this, -105f), Density.dip2px(this, 1f));
                break;
        }
    }

    public MainBottomPopupWindow showBottomPopupWindow(BottomPopType type,String subId) {
        View inflate = initPopView(type);
        mMainBottomPopupWindow = new MainBottomPopupWindow(this, inflate, type);
        if (type == BottomPopType.NA) {
            mMainBottomPopupWindow.setOnNAListener(new MainBottomPopupWindow.OnNAListener() {
                @Override
                public void onNA(String stampId, String naTypeId) {
                    sealByCard("", (stampIds, userId) -> {
                        if (stampIds == null || stampIds.size() == 0) {
                            ToastUtil.showCenterToast("无印章！");
                        } else {
                            String userId0 = SPUtil.getString(SPKey.Account.USER_ID);
                            if (mDialog == null)
                                mDialog = new LoadingDialog(MainRepairActivity.this);
                            if (!mDialog.isShowing()) mDialog.show();
                            StaticPresenter.stampNAInfo(userId0, mBillId, subId, userId, stampIds.get(0).stampId, naTypeId, new CallBack<Object>() {
                                @Override
                                public void onCompleted(Object o) {
                                    if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
                                    ToastUtil.showCenterToast("NA成功！");
                                    mMainBottomPopupWindow.dismiss();
                                    fixedAndLoad(mStep);
                                }

                                @Override
                                public void onError() {
                                    if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
                                    ToastUtil.showCenterToast("NA失败！");
//                            mMainBottomPopupWindow.dismiss();
                                }
                            });
                        }
                    });

                }
            });
        }
        mMainBottomPopupWindow.showAtLocation(mIvList, Gravity.BOTTOM, 0, 0);
        return mMainBottomPopupWindow;
    }

    private View initPopView(BottomPopType type) {
        switch (type) {
            case NA://N/A处理
                return LayoutInflater.from(this).inflate(R.layout.popwindow_na, null);
            case EngDisp://工程处理
                return LayoutInflater.from(this).inflate(R.layout.pop_engineering_disposal, null);
            case Seal://印章
                return LayoutInflater.from(this).inflate(R.layout.pop_seal, null);
            case Signature://签名
                return LayoutInflater.from(this).inflate(R.layout.pop_signature, null);
        }
        return null;
    }

    @Override
    public void onProgressItemClick(int index, boolean completed) {
//        if (!completed)
//            return;
        Intent intent = new Intent(this, MainSeeActivity.class);
        intent.putExtra("index", index);
        intent.putExtra("billId", mBillId);
        startActivity(intent);
    }

    public void updateProgress() {
        int currentPosition = mMainProgressTitle.getCurrentPosition();
        mMainContent.removeAllViews();
        if (mBaseView != null)
            mBaseView.release();
        switch (currentPosition) {
            case 0:
                mBaseView = new AcceptCheck(this);
                break;
            case 1:
                mBaseView = new BreakDownRecord(this);
                break;
            case 2:
                mBaseView = new CleanRecord(this);
                break;
            case 3:
                mBaseView = new CheckRecord(this);
                break;
            case 4:
                mBaseView = new SubProcess(this);
                break;
            case 5:
                mBaseView = new AssemblyRecord(this);
                break;
            case 6:
                mBaseView = new TestRecord(this);
                break;
            case 7:
                mBaseView = new FinalCheck(this);
                break;
        }
        mMainContent.addView(mBaseView.getItemView());
        mMainProgressTitle.updateProgress();
    }

    @Override
    protected void onDestroy() {
        mPopupWindow = null;
        if (mBaseView != null)
            mBaseView.release();
        if (mMainBottomPopupWindow != null) {
            if (mMainBottomPopupWindow.isShowing())
                mMainBottomPopupWindow.dismiss();
            mMainBottomPopupWindow = null;
        }
        mMainProgressTitle = null;
        super.onDestroy();
    }

    public void closeBottomPop() {
        if (mMainBottomPopupWindow != null && mMainBottomPopupWindow.isShowing())
            mMainBottomPopupWindow.dismiss();
    }

    public void showBigPic(ArrayList<String> data, int position) {
        Intent intent = new Intent(this, BigPicActivity.class);
        intent.putExtra("list", data);
        intent.putExtra("position", position);
        startActivity(intent);
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (mCanCard && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            tag = MCReader.patchTag(tag);
//            setTag(tag);
//            Utils.logUid(Utils.byte2Hex(tag.getId()));

            boolean isCopyUID = PreferencesUtil.getPreferences().getBoolean(
                    Constants.AutoCopyUID, false);
            if (isCopyUID) {
                int format = PreferencesUtil.getPreferences().getInt(
                        Constants.UIDFormat, 0);
                String fmtUID = Utils.byte2FmtString(tag.getId(), format);
            } else {
                // Show Toast message with UID.
                String msg = Utils.byte2Hex(tag.getId());
                LogUtil.i(msg);
                LoadingDialog loadingDialog = new LoadingDialog(this);
                loadingDialog.show();
                String userId = SPUtil.getString(SPKey.Account.USER_ID);
                StaticPresenter.getUserByCardId(userId, mBillId, stepId, msg, new CallBack<CardToSeal>() {
                    @Override
                    public void onCompleted(CardToSeal cardToSeal) {
                        loadingDialog.dismiss();
                        if (mNFCCallBack != null)
                            mNFCCallBack.onCallBack(cardToSeal.stamp, cardToSeal.userId);
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                    }

                    @Override
                    public void onError() {
                        loadingDialog.dismiss();
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                        ToastUtil.showCenterToast("获取印章失败！");
                    }
                });


            }
//            return Utils.checkMifareClassicSupport(tag, context);
        }
    }

    public void sealByCard(String id, NFCCallBack NFCCallBack) {
        if (NFCApp.hasWritePermissionToExternalStorage(MainRepairActivity.this)) {
            NFCApp.setUseAsEditorOnly(NFCApp.useAsEditorOnly());
            runStartUpNode(StartUpNode.FirstUseDialog);
            if (TextUtils.isEmpty(id))
                stepId = mStepId;
            else
                stepId = id;
            mNFCCallBack = NFCCallBack;
            if (mCardSealPop == null)
                mCardSealPop = new CardSealPop(this) {
                    @Override
                    protected void onDismiss1() {
                        mCanCard = false;
                    }
                };
            if (!mCardSealPop.isShowing())
                mCardSealPop.show();
//                mCardSealPop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            mCanCard = true;
        } else {
            ActivityCompat.requestPermissions(MainRepairActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);
        }
    }

    @Override
    public void finish() {
        if (mCardSealPop != null && mCardSealPop.isShowing()) {
            mCardSealPop.dismiss();
            return;
        }
        super.finish();
    }
    //    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (KeyEvent.KEYCODE_BACK == keyCode)
//            if (mCardSealPop != null && mCardSealPop.isShowing()) {
//                mCardSealPop.dismiss();
//                return true;
//            }
//        return super.onKeyDown(keyCode, event);
//    }
}
